import { Card, Col, Form, Icon, Row, Steps, message } from "antd";
// import TextArea from "antd/lib/input/TextArea";
import { addon } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import { MainCard } from "src/business/components/style-components/main-card";
import { MainContent } from "src/business/components/style-components/main-content";
import { AppServiceUtility } from "src/projects/app/appService";
import { ROUTE_PATH } from "src/projects/router";
import { IDCardReader, IDCard } from "src/business/device/id_card";
import PreliminaryAssessmentForm from "./preliminary-assessment-form";
import { UserEntry } from "src/projects/components/user-entry";
import { request_func } from "src/business/util_tool";
const { Step } = Steps;

/**
 * 组件：编辑登记状态
 */
export interface ChangereservationRegistrationViewState extends ReactViewState {
    /** 步骤 */
    current?: number;
    /** 模板集合 */
    template_list?: any[];
    /** 项目集合 */
    project_list?: any[];
    /** 项目列表 */
    item_list?: any[];
    /** 项目列表集合 */
    all_item_list?: any[];
    /** 需求模板列表 */
    requirement_template_list?: any[];
    /** 需求模板 */
    requirement_template?: any[];
    /** 表单值集合 */
    form_value_list?: {};
    /** 身份证 */
    id_card?: IDCard;
}
/**
 * 组件：编辑登记
 * 描述
 */
export class ChangereservationRegistrationView extends ReactView<ChangereservationRegistrationViewControl, ChangereservationRegistrationViewState> {
    constructor(props: any) {
        super(props);
        this.state = {
            current: 0,
            template_list: [],
            project_list: [],
            item_list: [],
            all_item_list: [],
            requirement_template_list: [],
            requirement_template: [],
            form_value_list: {},
        };
    }
    componentDidMount() {
        /** 获取评估模板那 */
        AppServiceUtility.assessment_template_service.get_assessment_template_list!({})!
            .then((data: any) => {
                if (data.result) {
                    this.setState({
                        template_list: data.result
                    });
                }
            });
        /** 获取需求项目 */
        // AppServiceUtility.requirement_project_service.get_list!({})!
        //     .then((data: any) => {
        //         if (data.result) {
        //             this.setState({
        //                 // requirement_template_list: data.result
        //                 item_list: data.result
        //             });
        //         }
        //     });
        /** 获取需求模板 */
        // AppServiceUtility.requirement_template_service.get_requirement_template_list!({})!
        //     .then((data: any) => {
        //         if (data.result) {
        //             this.setState({
        //                 requirement_template_list: data.result
        //             });
        //         }
        //     });
    }
    /** 选择模板选择框值改变 */
    template_change = (value: any) => {
        AppServiceUtility.assessment_template_service.get_assessment_template_list!({ id: value })!
            .then((data: any) => {
                if (data.result) {
                    this.setState({
                        project_list: data.result
                    });
                }
            });
    }
    /** 上一步 */
    prev = () => {
        let current = this.state.current! - 1;
        this.setState({ current });
        console.log(current, this.state.form_value_list);
        console.info(this.state.form_value_list);
    }
    // 基本资料
    infoSubmit = (err: any, values: any) => {
        console.log('这是联系人', values);
        if (!err) {
            let current = this.state.current! + 1;
            let formValue = this.state.form_value_list;
            values.personnel_category = '长者';
            formValue!['basic_information'] = {
                name: values['name'],
                id_card: values.id_card,
                id_card_type: '身份证',
                personnel_type: '1',
                remarks: values.remarks,
                personnel_info: values,
            };
            this.setState({
                current,
                form_value_list: formValue,
            });
            console.log('Received values of form: ', values);

        }
        console.info(this.state.form_value_list);
    }
    // 初步评估
    assSubmit = (err: any, value: any) => {
        console.info('初步评估');
        console.info(value);
        let current = this.state.current! + 1;
        let formValue = this.state.form_value_list;
        formValue!['preliminary_assessment'] = value;
        this.setState({
            form_value_list: formValue,
        });
        console.log('Received values of form: ', value);
        // 预约记录对象
        let reservation_registration = {};
        reservation_registration['remarks'] = formValue!['basic_information']['remarks'];
        reservation_registration['state'] = '现场预约';
        formValue!['reservation_registration'] = reservation_registration;
        console.info(formValue, current);
        request_func(this, AppServiceUtility.reservation_registration_service.update_reservation_registration, [formValue], (data: any) => {
            this.setState({ current });
            message.info(data === 'Success' ? '预约成功' : '预约失败');
        });
    }
    // 入住需求
    // residenceDemandSubmit = (e: any) => {
    //     console.info('入住需求');
    //     e.preventDefault();
    //     this.props.form.validateFields((err: any, values: any) => {
    //         if (!err) {
    //             let current = this.state.current! + 1;
    //             console.info(current);
    //             let formValue = this.state.form_value_list;
    //             formValue!['residence_demand'] = values;
    //             // 预约记录对象
    //             let reservation_registration = {};
    //             reservation_registration['remarks'] = formValue!['basic_information']['remarks'];
    //             reservation_registration['state'] = '现场预约';
    //             formValue!['reservation_registration'] = reservation_registration;
    //             console.info(formValue);
    //             const process = async () => {
    //                 let data = await AppServiceUtility
    //                     .reservation_registration_service
    //                     .update_reservation_registration!(formValue!)!;
    //                 message.info(data);
    //                 this.setState({ current });
    //             };

    //             process().then().catch(error => console.log(error));
    //         }
    //     });
    // }
    // /** 入住需求选项改变 */
    // itemOnChange = (value: any, option: any) => {
    //     let list: any[] = this.state.all_item_list!;
    //     AppServiceUtility.services_project_service.get_services_project_list!({ id: value })!
    //         .then((data: any) => {
    //             if (list.length > 0 && data) {
    //                 list[option.key] = data.result[0];
    //                 this.setState({
    //                     all_item_list: list
    //                 });
    //             }
    //         });
    // }
    /** 入住模板选择 */
    // requirementChange = (value: any) => {
    //     /** 获取需求模板 */
    //     AppServiceUtility.requirement_template_service.get_requirement_template_list!({ id: value }, 1, 1)!
    //         .then((data: any) => {
    //             if (data.result) {
    //                 this.setState({
    //                     all_item_list: data.result[0].dataSource,
    //                 });
    //             }
    //         });
    // }
    /** 处理身份证读取 */
    handleIDCardReader?() {
        // 调试环境下（npm start）驱动地址为/drive/ZKIDROnline.exe
        // 正式环境下（python）驱动地址为/download/build/www/drive/ZKIDROnline.exe
        const dev = process.env.NODE_ENV === 'development',
            drive_path = dev ? `/drive/ZKIDROnline.exe` : `/download/build/www/drive/ZKIDROnline.exe`;

        new IDCardReader(drive_path)
            .read_async!()!
            .then(id_card => {
                this.setState({ id_card });
            })
            .catch(error => {
                message.warning(error.message);
            });
    }
    /** 完成按钮 */
    complete = () => {
        this.props.history!.push(ROUTE_PATH.reservationRegistration);
    }
    /** 添加入住需求按钮 */
    addItem = () => {
        let list: any[] = this.state.all_item_list!;
        list.push({});
        this.setState({
            all_item_list: list
        });
    }
    componentWillMount() {
        console.info(this.props.match!.params);
        if (this.props.match!.params.key) {
            AppServiceUtility.reservation_registration_service.get_reservation_registration_list!({ id: this.props.match!.params.key }, 1, 1)!
                .then((data: any) => {
                    console.log('拿到的数据', data);
                    let value = {};
                    value['basic_information'] = data['result'][0]['basic_information'][0];
                    value['preliminary_assessment'] = data['result'][0]['preliminary_assessment'][0];
                    value['residence_demand'] = data['result'][0]['residence_demand'][0];
                    this.setState({
                        form_value_list: value
                    });

                })
                .catch((err: any) => {
                    console.info(err);
                });
        }
    }
    render() {
        // 通用信息配置
        // const formItemLayout1 = {
        //     labelCol: {
        //         xs: { span: 24 },
        //         sm: { span: 5 },
        //     },
        //     wrapperCol: {
        //         xs: { span: 24 },
        //         sm: { span: 16 },
        //     },
        // };
        // const { getFieldDecorator } = this.props.form!;
        let submit_btn_propps = {
            text: "下一步",
            cb: this.infoSubmit
        };
        let { current } = this.state;
        // 如果需求项目不为空则生成
        // let item_list;
        // if (this.state.all_item_list!.length > 0) {
        //     item_list = this.state.all_item_list!.map((value, index) => {
        //         return (
        //             <Card key={index}>
        //                 <Row type="flex" justify="center">
        //                     <Col span={12}>
        //                         <Form.Item label='需求项目'>
        //                             {getFieldDecorator('project_name___' + index, {
        //                                 initialValue: value.project_name ? value.project_name : '',
        //                                 rules: [{
        //                                     required: false,
        //                                     // message: '请选择需求项目'
        //                                 }],
        //                             })(
        //                                 <Select showSearch={true} key={value.requirement_projects} onChange={this.itemOnChange}>
        //                                     {this.state.item_list!.map((key) => {
        //                                         return <Select.Option key={index} value={key['id']}>{key['project_name']}</Select.Option>;
        //                                     })}
        //                                 </Select>
        //                             )}
        //                         </Form.Item>
        //                         {
        //                             value.requirement_options ? value.requirement_options.map((service_options: any, indexs: any) => {
        //                                 return (
        //                                     <Form.Item label={indexs + 1 + '、'} key={indexs}>
        //                                         {getFieldDecorator(service_options.id + '___' + indexs, {
        //                                             initialValue: '',
        //                                             rules: [{
        //                                                 required: false,
        //                                             }],
        //                                         })(
        //                                             <Radio.Group>
        //                                                 {
        //                                                     service_options.requirement_option.dataSource!.map((item: any, content: any) => {
        //                                                         return <p key={content}><Radio value={item.weight}>{item.option_content}</Radio></p>;
        //                                                     })
        //                                                 }
        //                                             </Radio.Group>
        //                                         )}
        //                                     </Form.Item>
        //                                 );
        //                             }) : ''
        //                         }
        //                     </Col>
        //                 </Row>
        //             </Card>
        //         );
        //     });
        // }
        // 入住需求
        // let residence_demand = (
        //     <Form {...formItemLayout1} onSubmit={this.residenceDemandSubmit}>
        //         <MainCard>
        //             <Row type="flex" justify="center">
        //                 <Col span={12}>
        //                     <Form.Item label='需求模板名称'>
        //                         {getFieldDecorator('reservation_template_name', {
        //                             initialValue: '',
        //                             rules: [{
        //                                 required: false,
        //                                 message: '需求模板名称'
        //                             }],
        //                         })(
        //                             <Select showSearch={true} onChange={this.requirementChange}>
        //                                 {this.state.requirement_template_list!.map((key, index) => {
        //                                     return <Select.Option key={index} value={key['id']}>{key['template_name']}</Select.Option>;
        //                                 })}
        //                             </Select>
        //                         )}
        //                     </Form.Item>
        //                     <Form.Item label='特殊要求'>
        //                         {getFieldDecorator('special_requirements', {
        //                             initialValue: '',
        //                             rules: [{
        //                                 required: false,
        //                                 message: '请输入特殊要求'
        //                             }],
        //                         })(
        //                             <Input />
        //                         )}
        //                     </Form.Item>
        //                     <Form.Item label='备注'>
        //                         {getFieldDecorator('remarks', {
        //                             initialValue: '',
        //                             rules: [{
        //                                 required: false,
        //                                 message: '请输入备注'
        //                             }],
        //                         })(
        //                             <Input />
        //                         )}
        //                     </Form.Item>
        //                 </Col>
        //             </Row>
        //         </MainCard>
        //         <MainCard>
        //             {item_list}
        //             <Button type='primary' onClick={this.addItem}>新增需求项目</Button>
        //         </MainCard>
        //     </Form>

        // );
        // 预约成功
        let success = (
            <Row type='flex' justify='center'>
                <Col span={8}>
                    <Row type='flex' justify='center'>
                        <Icon type="check-circle" style={{ fontSize: 200 }} theme="twoTone" twoToneColor="#52c41a" />
                    </Row>
                    <Row type='flex' justify='center'>
                        预约成功
                    </Row>
                    <Row type='flex' justify='center'>
                        长者姓名：{this.state.form_value_list!['basic_information'] ? this.state.form_value_list!['basic_information'].name : ''}
                    </Row>
                    <Row type='flex' justify='center'>
                        身份证号码:{this.state.form_value_list!['basic_information'] ? this.state.form_value_list!['basic_information'].id_card : ''}
                    </Row>
                    {/* <Row type='flex' justify='center'>
                        预约时间：2019-07-29 16:31
                    </Row> */}
                </Col>
            </Row>
        );
        let steps = [
            {
                title: '基本资料',
                content: (<UserEntry base_info={this.state.form_value_list!['basic_information']} is_detailed_info={false} base_info_submit_btn_propps={submit_btn_propps} />)
            },
            {
                title: '初步评估',
                content: (
                    <Card>
                        <PreliminaryAssessmentForm formSubmit={this.assSubmit} lastStep={this.prev} baseData={this.state.form_value_list!['preliminary_assessment']} />
                    </Card>
                )
            },
            // {
            //     title: '入住需求',
            //     content: residence_demand
            // },
            {
                title: '预约成功',
                content: success
            },
        ];
        return (
            <MainContent>
                <MainCard title='预约登记'>
                    <Steps current={current}>
                        {steps.map(item => (
                            <Step key={item.title} title={item.title} />
                        ))}
                    </Steps>
                    <MainContent />
                    {steps[current!].content}
                    {/* <Row type="flex" justify='center'>
                        {current !== 0 && current! < steps.length - 1 && (
                            current === 1 ?
                                '' :
                                <div>
                                    <Button onClick={this.prev}>
                                        上一步
                                    </Button>
                                    <Button onClick={this.residenceDemandSubmit}>
                                        下一步
                                    </Button>
                                </div>
                        )}
                        {current === steps.length - 1 && (
                            <Button type="primary" onClick={this.complete}>
                                完成
                            </Button>
                        )}
                    </Row> */}
                </MainCard>
            </MainContent>
        );
    }
}
/**
 * 控件：编辑登记
 * 描述
 */
@addon('ChangereservationRegistrationView', '编辑登记', '描述')
@reactControl(Form.create<any>()(ChangereservationRegistrationView), true)
export class ChangereservationRegistrationViewControl extends ReactViewControl {
}